#!/bin/bash
set -e
set -x
MYDIR="${0%/*}"
cd "$MYDIR/.."
source "recipes/common.sh"


# RECIPE START firmware-linux
# depends: xz-native

VERSION=20220310
TARBALL="linux-firmware-${VERSION}.tar.xz"

unset NIL

rm -rf build/firmware-linux
mkdir -p build/firmware-linux
buildroot="`pwd`/build/firmware-linux/inst${prefix}"
mkdir -p -m755 "$buildroot"

tar -x -a -v -f "${TARBALL}" -C build/firmware-linux --strip-components=1
make -C build/firmware-linux \
	install \
	DESTDIR="$buildroot" \
	FIRMWAREDIR="/lib/firmware" \
	$NIL

find $buildroot/lib/firmware -type f -not -name '*.xz' -print0 | xargs -0 -n 100 -P `nproc` xz -C crc32 -T1
# fix broken symlinks: lnk -> foo => lnk.xz -> foo.xz
find $buildroot/lib/firmware -xtype l -not -name '*.xz' -printf '%l.xz\0%p.xz\0' | xargs -0 -n 2 ln -sf
find $buildroot/lib/firmware -xtype l -not -name '*.xz' -delete
# bail out if some symlinks are still broken
test `find $buildroot/lib/firmware -xtype l | wc -l` -eq 0
# Replace same files with hardlinks
if command -v hardlink 2>/dev/null; then
	hardlink -cv $buildroot/lib/firmware
fi

cd build/firmware-linux/inst
find "${prefix#/}" | cpio -pumd "$stage"
cd ../../..
# rm -rf build/firmware-linux


# RECIPE END firmware-linux
